package domain;

import org.hibernate.annotations.Parent;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;

/**
 * hibernate组件属性
 */
@Embeddable
public class Name {
    @Column(name = "first_name")
    private String first;
    @Column(name = "last_name")
    private String last;
    //注解此组件的拥有者
    @Parent
    private Student student;

    //组件的属性为集合
    @ElementCollection(targetClass = Integer.class, fetch = FetchType.LAZY)
    @CollectionTable(name = "student_name_power",
        joinColumns = @JoinColumn(name = "student_name_id", nullable = false))
    @Column(name = "name_power",nullable = false)
    @MapKeyClass(String.class)
    @MapKeyColumn(name = "name_aspect")
    private Map<String,Integer> power = new HashMap<>();

    public Name() {
    }

    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    @Override
    public String toString() {
        return "<Name: "+getFirst()+", "+getLast()+","+getPower()+">";
    }

    @Override
    public int hashCode() {
        return getFirst().hashCode()*31+getLast().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(obj != null && obj.getClass() == this.getClass()){
            Name n  = (Name) obj;
            return n.getFirst().equals(getFirst()) && n.getLast().equals(getLast());
        }
        return false;
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public Map<String, Integer> getPower() {
        return power;
    }

    public void setPower(Map<String, Integer> power) {
        this.power = power;
    }
}
